// ==UserScript==
// @name         监控中心增强
// @namespace    http://doubly.top
// @version      2.1.3
// @description  解决监控中心需要频繁登录的问题，当弹出登录页面时，自动登录；自动关闭密码修改弹窗；给所有的搜索加上回车快捷键；针对挂起列表自动刷新（NEW）；
// @author       Doubly
// @include      https://tax.kdzwy.com/taxcaution/login
// @include      https://tax.kdzwy.com/taxcaution//login
// @include      https://tax.kdzwy.com/taxcaution/index
// @include      https://mtax.kdzwy.com/taxcaution/login
// @include      https://mtax.kdzwy.com/taxcaution//login
// @include      https://mtax.kdzwy.com/taxcaution/index
// @include      http://localhost:18081/login
// @include      http://localhost:18081//login
// @include      http://localhost:18081/index
// @icon         https://tax.kdzwy.com/taxcaution/favicon.ico
// @grant        GM_registerMenuCommand
// @grant        GM_setValue
// @grant        GM_getValue
// @require      https://cdn.jsdelivr.net/npm/sweetalert2@11
// ==/UserScript==

(function () {
    'use strict';

    let activeFrame = null;
    let observer = null;
    let autoRefreshInterval = null;
    let currentIframeDocument = null;

        // 创建设置选项菜单
    GM_registerMenuCommand('配置设置', openSettings);

    // 打开设置菜单
    function openSettings() {
        // 从油猴中读取已经保存的账号密码信息
        const devUsername = GM_getValue('devUsername', '');
        const devPassword = GM_getValue('devPassword', '');
        const mockUsername = GM_getValue('mockUsername', '');
        const mockPassword = GM_getValue('mockPassword', '');
        const prodUsername = GM_getValue('prodUsername', '');
        const prodPassword = GM_getValue('prodPassword', '');

        // 设置菜单的 HTML
        const settingsHTML = `
            <div style="padding: 20px;">
                <h3>开发环境</h3>
                <div style="margin-bottom: 10px;">
                    <label for="devUsername" style="display: inline-block; width: 80px;">用户名：</label>
                    <input type="text" id="devUsername" value="${devUsername}">
                </div>
                <div style="margin-bottom: 10px;">
                    <label for="devPassword" style="display: inline-block; width: 80px;">密码：</label>
                    <input type="password" id="devPassword" value="${devPassword}">
                </div>

                <h3>模拟环境</h3>
                <div style="margin-bottom: 10px;">
                    <label for="mockUsername" style="display: inline-block; width: 80px;">用户名：</label>
                    <input type="text" id="mockUsername" value="${mockUsername}">
                </div>
                <div style="margin-bottom: 10px;">
                    <label for="mockPassword" style="display: inline-block; width: 80px;">密码：</label>
                    <input type="password" id="mockPassword" value="${mockPassword}">
                </div>

                <h3>生产环境</h3>
                <div style="margin-bottom: 10px;">
                    <label for="prodUsername" style="display: inline-block; width: 80px;">用户名：</label>
                    <input type="text" id="prodUsername" value="${prodUsername}">
                </div>
                <div style="margin-bottom: 10px;">
                    <label for="prodPassword" style="display: inline-block; width: 80px;">密码：</label>
                    <input type="password" id="prodPassword" value="${prodPassword}">
                </div>
            </div>
      `;

        // 弹出设置框
        Swal.fire({
            title: '配置设置',
            html: settingsHTML,
            showCancelButton: true,
            showConfirmButton: true,
            allowOutsideClick: true,
            allowEscapeKey: true,
            focusConfirm: false,
            preConfirm: () => {
                saveConfigSettings();
            }
        });
    }

    /**
     * 保存配置信息到油猴中
     */
    function saveConfigSettings() {
        const devUsername = document.getElementById('devUsername').value;
        const devPassword = document.getElementById('devPassword').value;
        const mockUsername = document.getElementById('mockUsername').value;
        const mockPassword = document.getElementById('mockPassword').value;
        const prodUsername = document.getElementById('prodUsername').value;
        const prodPassword = document.getElementById('prodPassword').value;

        // 使用 GM_setValue 函数保存账号密码信息
        GM_setValue('devUsername', devUsername);
        GM_setValue('devPassword', devPassword);
        GM_setValue('mockUsername', mockUsername);
        GM_setValue('mockPassword', mockPassword);
        GM_setValue('prodUsername', prodUsername);
        GM_setValue('prodPassword', prodPassword);

        // 弹出保存成功的提示
        Swal.fire({
            icon: 'success',
            title: '保存成功',
            showConfirmButton: false,
            timer: 1500
        }).then(() => {
            // 关闭弹窗
            Swal.close();
        });
    }

    let username = '';
    let password = '';

    // 获取当前的url
    let url = window.location.href;
    // 判断当前打开的环境
    if (url.includes('mtax')) {
        // 模拟环境
        username = GM_getValue('mockUsername', '');
        password = GM_getValue('mockPassword', '');
    } else if (url.includes('tax')) {
        // 生产环境
        username = GM_getValue('prodUsername', '');
        password = GM_getValue('prodPassword', '');
    } else {
        // 开发环境
        username = GM_getValue('devUsername', '');
        password = GM_getValue('devPassword', '');
    }

    // 创建一个MutationObserver实例
    observer = new MutationObserver(function (mutationsList, observer) {
        // 遍历所有的变动
        let iframe = null;
        for (var mutation of mutationsList) {
            // 检查是否是style属性的变动
            if (mutation.type === 'attributes' && mutation.attributeName === 'style') {
                // 在此处处理style属性变化的逻辑
                // 获取发生变化的iframe
                // display:inline的iframe为当前启用的iframe
                if (mutation.target.style.display === 'inline') {
                    iframe = mutation.target;
                    break;
                }
            } else if (mutation.type === 'childList'){
                // 增加或删除了标签页
                if (mutation.removedNodes.length === 1){
                    console.log('删除了标签页', mutation.removedNodes[0].src);
                    // 这里可以增加所有标签页移除时要执行的逻辑
                } else if (mutation.addedNodes.length === 1){
                    console.log('新增了标签页', mutation.addedNodes[0].src);
                    iframe = mutation.addedNodes[0];
                    setTimeout(() => {
                        // 这里可以增加所有标签页需要初始化的逻辑
                        addEnterSearch(false, iframe);
                    }, 2000);
                    break;
                } else{
                    console.log('多个标签页数量发生变化');
                }
            }
        }
        if (iframe) {
            // 切换iframe之前执行逻辑
            cancelAutoRefresh();

            // 睡眠两秒
            setTimeout(() => {
                currentIframeDocument = iframe.contentDocument;
                activeFrame = iframe;
                // 这里可以增加所有标签页切换时要执行的逻辑
                addAutoRefreshForHuangup();
            }, 2000);
        }
    });
    // 配置MutationObserver监视的选项
    let config = {
        attributes: true,
        childList: true,
        subtree: true
    };

    window.onload = function () {
        console.log("页面加载完成");
        if (url.includes('login')) {
            console.log('检测到登录页面');
            login();
        } else {
            // 开始监听iframe的变化
            let content = document.getElementById('content-main');
            observer.observe(content, config);
            // 关闭密码修改弹窗
            closePasswordChangeLayer();

            // 获取当前激活的iframe
            let activeIframe = getActiveIframe();
            currentIframeDocument = activeIframe.contentDocument;

            // 增加回车查询事件
            addEnterSearch(true, activeIframe);
            // 增加自动刷新事件
            addAutoRefreshForHuangup();
        }
    }

    function addAutoRefreshForHuangup(){
        // 获取当前打开的标签页
        /*let tabName = "";
        let els = document.getElementsByTagName('a');
        for (let i = 0; i < els.length; i++) {
            let el = els[i];
            let className = el.className;
            if (className.includes("menuTab") && className.includes("active") && !className.includes("noactive")){
                tabName = el.innerText.trim();
                console.log('当前打开的标签页：' + tabName);
            }
        }*/

        //移除之前的自动刷新定时器
        if (autoRefreshInterval != null){
            cancelAutoRefresh();
        }

        // 增加一个自动刷新的开关
        addRefreshBtn();
    }

    /**
     * 取消自动刷新
     */
    function cancelAutoRefresh(){
        //移除之前的定时器
        if (autoRefreshInterval != null){
            console.log('取消自动刷新');
            clearInterval(autoRefreshInterval);
            autoRefreshInterval = null;
            setRefreshStatus();
        }
    }

    function addRefreshBtn(){
        let searchBtn = currentIframeDocument.getElementById('doublyRefreshBtn');
        if (searchBtn){
            return;
        }
        // 获取按键组
        // let toolbar = iframeDocument.getElementsByClassName('columns columns-right btn-group pull-right')[0];
        let toolbar = currentIframeDocument.getElementById('toolbar');
        if (!toolbar){
            return;
        }
        // 增加一个刷新开关
        let refreshBtn = currentIframeDocument.createElement('i');
        refreshBtn.className = 'fa fa-toggle-off fa-lg';
        refreshBtn.innerText = '自动刷新';
        refreshBtn.style['cursor'] = 'pointer';
        refreshBtn.style['font-size'] = 'larger';

        // 增加点击事件
        refreshBtn.onclick = function(){
            if (autoRefreshInterval != null){
                cancelAutoRefresh();
            } else {
                console.log('开始自动刷新');
                refreshBtn.className = 'fa fa-toggle-on fa-lg';
                //设置新的定时器刷新页面
                let iframeEls = currentIframeDocument.getElementsByTagName('a');
                let searchBtn = null;
                //获取搜索按钮
                for (let i = 0; i < iframeEls.length; i++) {
                    let el = iframeEls[i];
                    if (el.innerText.includes('搜索')){
                        searchBtn = el;
                        break;
                    }
                }
                autoRefreshInterval = setInterval(function () {
                    searchBtn.click();
                    // console.log('自动刷新：点击搜索')
                }, 1000 * 10);
            }
        }

        let divEl = currentIframeDocument.createElement("div");
        divEl.className = 'btn btn-default btn-outline';
        divEl.id = 'doublyRefreshBtn';
        divEl.appendChild(refreshBtn);

        toolbar.appendChild(divEl);
        // toolbar.insertBefore(divEl, toolbar.firstChild);
    }

    /**
     * 设置刷新按钮的状态
     */
    function setRefreshStatus() {
        let searchBtn = currentIframeDocument.getElementById('doublyRefreshBtn');
        let iconNode = searchBtn.childNodes[0];
        if(searchBtn){
            if (autoRefreshInterval){
                iconNode.className = 'fa fa-toggle-on fa-lg';
            }else{
                iconNode.className = 'fa fa-toggle-off fa-lg';
            }
        }
    }

    /**
     * 增加回车查询事件
     */
    function addEnterSearch(isFirst, activeIframe) {

        let iframeDocument = activeIframe.contentDocument;
        if (isFirst) {
            // 给当前页面的文本框增加回车查询事件
            addEnterEventForTextInput(iframeDocument);
            // 再次给iframe增加属性变化监听事件
            // observer.observe(activeIframe, config);
        } else {
            // 给当前页面的文本框增加回车查询事件
            addEnterEventForTextInput(iframeDocument);
        }
    }

    /**
     * 登录
     */
    function login() {
        console.log('输入用户名：' + username);
        let inputElement = document.getElementsByTagName('input')[0];
        inputElement.value = username;

        console.log('输入密码：' + password);
        inputElement = document.getElementsByTagName('input')[1];
        inputElement.value = password;

        console.log('点击登录按钮')
        // 获取登录按钮
        let loginBtn = document.getElementById("btnSubmit");
        // 点击登录按钮
        setTimeout(function () {
            loginBtn.click();
        }, 500);

    }

    /**
     * 关闭密码修改弹窗
     */
    function closePasswordChangeLayer() {
        console.log('关闭密码修改弹窗');
        let layer = document.getElementById('layui-layer1');
        if (layer) {
            console.log('检测到弹出层');
            let closeBtn = document.getElementsByClassName('layui-layer-close1')[0];
            closeBtn.click();
        } else {
            console.log('未检测到弹出层');
        }
    }

    /**
     * 获取当前激活的iframe
     */
    function getActiveIframe() {
        //获取所有的iframe
        let iframes = document.getElementsByTagName('iframe');

        //遍历所有的iframe，增加属性变化监听事件
        for (let i = 0; i < iframes.length; i++) {
            let iframe = iframes[i];
            // 开始监视iframe的属性变化
            if (iframe.style.display !== 'none') {
                return iframe;
            }
        }
    }

    /**
     * 给所有的文本输入框增加回车查询事件
     */
    function addEnterEventForTextInput(iframeDocument) {
        console.log('给所有的文本输入框增加回车查询事件');
        //给所有的文本输入框增加回车查询事件
        let inputElements = iframeDocument.getElementsByTagName('input');
        for (let i = 0; i < inputElements.length; i++) {
            let inputElement = inputElements[i];
            // 非文本输入框跳过
            if (inputElement.type !== 'text') {
                continue;
            }
            inputElement.addEventListener('keyup', function (event) {
                if (event.keyCode === 13) {
                    event.preventDefault();
                    // 通过a标签和包含“搜索”字样来获取查询按钮
                    let queryBtn;
                    iframeDocument.getElementsByTagName('a').forEach((item) => {
                        if (item.innerText.includes('搜索')) {
                            queryBtn = item;
                        }
                    });
                    // 点击查询按钮
                    queryBtn.click();
                }
            });
        }
    }

})();
